package by.grsu.samusev.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.samusev.entity.Voyage;
import by.grsu.samusev.table.VoyageTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class VoyageDao  extends AbstractDao<VoyageTable, Voyage>{

	/**
	 * 
	 */
	private static final long serialVersionUID = -2642153105086864918L;

	public VoyageDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public Long saveNew(final Voyage newVoyage) {
		Long nextId = getNextId();
				newVoyage.setId(nextId);
				final VoyageTable voyageTable = deserializeFromXml();
				voyageTable.getRows().add(newVoyage);
				serializeToXml(voyageTable);
				return nextId;
			}

	@Override
	public void update(final Voyage entity) {
		final VoyageTable voyageTable = deserializeFromXml();
		for (final Voyage row : voyageTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				row.setId(entity.getId());
				row.setDriverId(entity.getDriverId());
				row.setStatus(entity.getStatus());
				break;
			}
		}
		serializeToXml(voyageTable);

	}
	@Override
	public Voyage get(final Serializable id) {
		final VoyageTable voyageTable = deserializeFromXml();
		for (final Voyage row : voyageTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Voyage> getAll() {
		final VoyageTable voyageTable = deserializeFromXml();
		return voyageTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
				final VoyageTable voyageTable = deserializeFromXml();
				Voyage toBeDeleted = null;
				for (final Voyage row : voyageTable.getRows()) {
					if (row.getId().equals(id)) {
						toBeDeleted = row;
						break;
					}
				}
				voyageTable.getRows().remove(toBeDeleted);
				serializeToXml(voyageTable);
		}

	@Override
	protected Class<VoyageTable> getTableClass() {
		return VoyageTable.class;
	}

}
